#!/usr/bin/env python2.5
# $Id: test2-52.py 312eedc3abd6 2012/09/23 00:20:44 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# File test2-52.py generated on Friday September 21, 2012 @ 23:10:31 PDT
#

__version__  = "$Revision: 312eedc3abd6 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-09-23 00:20:44Z $"

import getpass
import urllib2
import urllib

username = raw_input("Enter email: ")
password = getpass.getpass("Enter password: ")

def get_opener(cookiejar=None):
   opener = urllib2.OpenerDirector()
   opener.add_handler(urllib2.ProxyHandler())
   opener.add_handler(urllib2.UnknownHandler())
   opener.add_handler(urllib2.HTTPHandler())
   opener.add_handler(urllib2.HTTPDefaultErrorHandler())
   opener.add_handler(urllib2.HTTPErrorProcessor())
   opener.add_handler(urllib2.HTTPSHandler())
   if cookiejar:
      opener.add_handler(urllib2.HTTPCookieProcessor(cookiejar))

   return opener

def get_google_authtoken(appname, email_address, password):
   opener = get_opener()
   # get an AuthToken from Google accounts
   auth_uri = 'https://www.google.com/accounts/ClientLogin'
   authreq_data = urllib.urlencode({
          "Email":   email_address,
          "Passwd":  password,
          "service": "ah",
          "source":  appname,
          "accountType": "HOSTED_OR_GOOGLE" })
   req = urllib2.Request(auth_uri, data=authreq_data)
   try:
      response = opener.open(req)
      response_body = response.read()
      response_dict = dict(ix.split("=")
            for ix in response_body.split("\n") if ix)
      return response_dict["Auth"]
   except urllib2.HTTPError, err:
      if err.code == 403:
         body = err.read()
         response_dict = dict(ix.split("=", 1) for ix in body.split("\n") if ix)
         raise ValueError, err.code
         # print(req.get_full_url(), e.code, e.msg, e.headers, response_dict)
      else:
         raise

auth = get_google_authtoken("testapp", username, password)
print(auth)
